package io.sundial.console;

import com.google.common.base.Optional;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 丽晶中台未知异常处理器
 *
 * @author 杨昌沛 646742615@qq.com
 * 2018/10/8
 */
public class UnexpectedExceptionHandler implements HandlerExceptionResolver, Ordered {

    @Override
    public int getOrder() {
        return -1;
    }

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView mav = new ModelAndView();
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        Map<String, Object> attributes = new LinkedHashMap<>();
        attributes.put("code", -1);
        attributes.put("message", Optional.fromNullable(ex.getMessage()).or(ex.getClass().getSimpleName()));
        view.setAttributesMap(attributes);
        mav.setView(view);
        return mav;
    }


}
